import { constantRoutes, historyRoutes, supplierRoutes } from "@/router";
import store from "@/store";
import { ACCESS_TOKEN } from "@/config/common";
import { loginMD5, arrayFormat } from "@/utils/index";
import {
  getMine,
  logout,
  login,
  getAllTree,
  getAllRole,
  getAllUser,
  getAllDepartment,
  getAllDepartmentSelect,
  getAllPosition,
  getMaterialTypeSelect,
  getProjectSelect,
  roleIdGetUserSelect,
  purchaseBidLog,
  uploads,
  regUploads
} from "@/api/common_api";

function hasPermission(roles, route) {
  if (roles && roles.length !== 0) {
    return roles.some(role => role.code.includes(route.name));
  } else {
    return true;
  }
}
export function filterAsyncRoutes(routes, roles) {
  const res = [];
  routes.forEach(route => {
    const tmp = { ...route };
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles);
      }
      res.push(tmp);
    }
  });
  return res;
}

const state = {
  user: {},
  sign: false,
  //routes: constantRoutes,
  routes: [],
  btns: [],
  token: ""
};

const mutations = {
  RESET_STATE: () => {
    sessionStorage.removeItem(ACCESS_TOKEN);
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USER: (state, data) => {
    state.user = data;
  },
  SET_SIGN: (state, sign) => {
    state.sign = sign;
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes;
  },
  SET_BTNS: (state, btns) => {
    state.btns = btns;
  }
};

const actions = {
  login({ commit }, userInfo) {
    const { account, pwd, captcha, captchaKey } = userInfo;
    return new Promise((resolve, reject) => {
      login({
        account: account.trim(),
        pwd: loginMD5(pwd),
        captchaKey: captchaKey,
        captcha: captcha
      })
        .then(async res => {
          if (res.code === 200) {
            sessionStorage.setItem(ACCESS_TOKEN, res.data.token);
            //commit('SET_USER',res.data.user);
            if (res.data.user.supplierName) {
              resolve(1);
            } else {
              getMine().then(res => {
                let menus = res.data.menus;
                const isShow = menus.some(v => v.code === "boardCode");
                const isstate = isShow ? 2 : 3;
                resolve(isstate);
              });
            }
          }
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  generateRoutes({ commit }) {
    return new Promise((resolve, reject) => {
      getMine()
        .then(res => {
          if (res.code === 200) {
            let menus = res.data.menus;
            if (menus && menus.length !== 0) {
              let _menus = [];
              menus.forEach(v => {
                let params = {};
                params.code = v.code;
                params.name = v.name;
                _menus.push(params);
                if (v.children && v.children.length !== 0) {
                  v.children.forEach(el => {
                    let child = {};
                    child.code = el.code;
                    child.name = el.name;
                    _menus.push(child);
                  });
                }
              });
              let accessedRoutes = filterAsyncRoutes(constantRoutes, _menus);
              if (res.data.purchaseSupplier == null) {
                let newAccessedRoutes = historyRoutes.concat(accessedRoutes);
                commit("SET_ROUTES", newAccessedRoutes);
                resolve(newAccessedRoutes);
              } else {
                let newAccessedRoutes = supplierRoutes.concat(accessedRoutes);
                commit("SET_ROUTES", newAccessedRoutes);
                resolve(newAccessedRoutes);
              }
            } else {
              let newAccessedRoutes = supplierRoutes
                .concat(historyRoutes)
                .concat(constantRoutes);
              commit("SET_ROUTES", newAccessedRoutes);
              resolve(newAccessedRoutes);
            }
            commit("SET_BTNS", res.data.roles[0].permissions);
            commit("SET_USER", res.data);

            commit("SET_SIGN", true);
          }
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  resetRoutes({ commit }, data) {
    commit("SET_SIGN", data);
  },

  logout({ commit }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(async () => {
          await store.dispatch("user/resetRoutes", false);
          commit("RESET_STATE");
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  resetToken({ commit }) {
    return new Promise(async resolve => {
      await store.dispatch("user/resetRoutes", false);
      commit("RESET_STATE");
      resolve();
    });
  },
  //权限
  getAllTree({ commit }) {
    return new Promise(async (resolve, reject) => {
      getAllTree()
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  //用户
  getAllUser({ commit }) {
    return new Promise(async (resolve, reject) => {
      getAllUser()
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  //角色
  getAllRole({ commit }) {
    return new Promise(async (resolve, reject) => {
      getAllRole()
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  //角色id获取用户列表
  roleIdGetUserSelect({ commit }, roleId) {
    return new Promise(async (resolve, reject) => {
      roleIdGetUserSelect(roleId)
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  //标操作记录
  purchaseBidLog({ commit }, data) {
    return new Promise(async (resolve, reject) => {
      purchaseBidLog(data)
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  //部门
  getAllDepartment({ commit }) {
    return new Promise(async (resolve, reject) => {
      getAllDepartment()
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  getAllDepartmentSelect({ commit }) {
    return new Promise(async (resolve, reject) => {
      getAllDepartmentSelect()
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  //职位
  getAllPosition({ commit }) {
    return new Promise(async (resolve, reject) => {
      getAllPosition()
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  //分类
  getMaterialTypeSelect({ commit }, id) {
    return new Promise(async (resolve, reject) => {
      getMaterialTypeSelect(id)
        .then(res => {
          const _data = arrayFormat(res.data);
          resolve(_data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  //项目库
  getProjectSelect({ commit }) {
    return new Promise(async (resolve, reject) => {
      getProjectSelect()
        .then(res => {
          resolve(res.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  uploadFile({ commit }, payload) {
    const { fileKey, data } = payload;
    let formData = new FormData();
    formData.append("file", data.file);
    return new Promise(async (resolve, reject) => {
      let { code, data } = await uploads(fileKey, formData);
      if (code === 200) {
        let url = `${process.env.VUE_APP_FILE}${data}`;
        resolve(url);
      }
    });
  },
  regUploadFile({ commit }, payload) {
    const { fileKey, data } = payload;
    let formData = new FormData();
    formData.append("file", data.file);
    return new Promise(async (resolve, reject) => {
      let { code, data } = await regUploads(fileKey, formData);
      if (code === 200) {
        let url = `${process.env.VUE_APP_FILE}${data}`;
        resolve(url);
      }
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
